package com.js.rtu.fragment.first;


import android.Manifest;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;

import com.js.rtu.R;
import com.js.rtu.base.BaseMainFragment;
import com.js.rtu.event.StartBrotherEvent;
import com.js.rtu.util.ToastUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;


public class FirstTabFragment extends BaseMainFragment {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.frg_fitter)
    FrameLayout frgFitter;


    private Disposable permissionDisposable;

    public static FirstTabFragment newInstance() {
        Bundle args = new Bundle();
        FirstTabFragment fragment = new FirstTabFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_first;
    }

    @Override
    protected void initView() {
        loadRootFragment(R.id.frg_first, BleListFragment.newInstance());
        loadRootFragment(R.id.frg_fitter, FitterFragment.newInstance());
        toolbarTitle.setText(R.string.navigation_title_connect);
        toolbar.inflateMenu(R.menu.menu_scan);
        toolbar.inflateMenu(R.menu.map_fitter);
        toolbar.setOnMenuItemClickListener(item -> {
            switch (item.getItemId()) {
                case R.id.action_scan:
                    toScan();
                    break;
                case R.id.action_fitter:
                    if (frgFitter.getVisibility() == View.VISIBLE) {
                        frgFitter.setVisibility(View.GONE);
                    } else {
                        frgFitter.setVisibility(View.VISIBLE);
                    }
                    break;
            }
            return true;
        });

    }

    /**
     * 扫一扫
     */
    private void toScan() {
        permissionDisposable = new RxPermissions(_mActivity)
                .request(Manifest.permission.CAMERA)
                .subscribe(granted -> {
                    if (granted) { // Always true pre-M
                        EventBus.getDefault().post(new StartBrotherEvent(QRCodeFragment.newInstance()));
                    } else {
                        ToastUtil.warning("请打开权限");
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (permissionDisposable != null)
            permissionDisposable.dispose();
    }


}
